package com.inossem.warehousemanage_tv.iot;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;

public class SendSocketData {
    public OnButtonClickListener listener = null;
    private String HOST;
    private int PORT;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String s = (String) msg.obj;
            listener.onButtonClick(s);
        }
    };

    public SendSocketData(String HOST, int PORT) {
        this.HOST = HOST;
        this.PORT = PORT;
        test();
    }

    private void test() {
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Socket socket = null;
                DataInputStream dis = null;
                InputStream is = null;
                try {
                    socket = new Socket(HOST, PORT);
                    is = socket.getInputStream();
                    dis = new DataInputStream(is);
                    while (true) {
                        System.out.println("receive_msg:" + dis.readUTF());
                        Message message = handler.obtainMessage();
                        message.obj = dis.readUTF();
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Looper.loop();
            }
        }.start();
    }

    public void setOnButtonClickListener(OnButtonClickListener l) {
        listener = l;
    }

    public interface OnButtonClickListener {
        void onButtonClick(String s);
    }
}